package com.sise.parkinglot.composition;

import com.auth0.jwt.JWT;
import com.sise.parkinglot.entity.Park;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author ZJ
 */
@Component
public class PublicService {

    /**
     * 将字符串转用md5加密
     *
     * @param value 加密值
     * @return 加密后的值
     */
    public String md5Encryption(String value) {
        return DigestUtils.md5DigestAsHex(value.getBytes());
    }

    /**
     * 根据token获取用户id
     *
     * @param token token
     * @return 用户id
     */
    public String getUserIdByToken(String token) {
        return JWT.decode(token).getClaim("id").asString();
    }


    /**
     * @param parkList 停车记录
     * @return 计算收益
     */
    public AtomicReference<BigDecimal> getIncome(List<Park> parkList) {
        AtomicReference<BigDecimal> income = new AtomicReference<>(new BigDecimal(0));
        parkList.forEach(r -> {
            if (r.getFee() != null) {
                BigDecimal current = income.get();
                BigDecimal next = current.add(r.getFee());
                income.compareAndSet(income.get(), next);
            }
        });
        return income;
    }

    /**
     * @param dt 日期
     * @return 星期几
     */
    public String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * @param past 天数
     * @return 计算日期
     */
    public Date getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        return calendar.getTime();
    }
}
